package com.hkjtgc.pcr_app.ui

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.view.View
import android.widget.EditText
import androidx.annotation.RequiresApi
import com.hkjtgc.pcr_app.R
import com.hkjtgc.pcr_app.util.Constant
import com.hkjtgc.pcr_app.util.SharedPreferencesUtils
import com.hkjtgc.pcr_app.util.ToastUtil
import com.king.zxing.CaptureActivity
import com.king.zxing.DecodeConfig
import com.king.zxing.analyze.MultiFormatAnalyzer
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@RequiresApi(Build.VERSION_CODES.O)
class QRCodeActivity : CaptureActivity(), View.OnClickListener {
    override fun getLayoutId(): Int {
        return R.layout.activity_qr_code
    }

    private var simpleId: String? = null
    private var cardBoxId: String? = null
    //var type = 1

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(R.layout.activity_qr_code)
//        type = intent.getIntExtra("type", 1)
//        findViewById<AppCompatTextView>(R.id.qr_code).text = BindUtils.typeQATitleList[type]
//        findViewById<AppCompatTextView>(R.id.tv_dialog_show).text = BindUtils.typeQAButtonList[type]
    }

    override fun onResume() {
        super.onResume()
//        type = intent.getIntExtra("type", 1)
//        findViewById<AppCompatTextView>(R.id.qr_code).text = BindUtils.typeQATitleList[type]
//        findViewById<AppCompatTextView>(R.id.tv_dialog_show).text = BindUtils.typeQAButtonList[type]
    }

    @SuppressLint("Range")
    override fun initCameraScan() {
        super.initCameraScan()

        //初始化解码配置
        val decodeConfig = DecodeConfig()
        decodeConfig
            .setFullAreaScan(false)
            .setAreaRectRatio(0.8f)
            .setAreaRectVerticalOffset(0).areaRectHorizontalOffset = 0


        //在启动预览之前，设置分析器
        cameraScan
            .setVibrate(false)
            .setNeedAutoZoom(true)
            .setPlayBeep(true)
            .setAnalyzer(MultiFormatAnalyzer(decodeConfig))

        cameraScan.setOnScanResultCallback {
//            findViewById<AppCompatTextView>(R.id.tv_scan_data).text = it.text
//            val map = Gson().fromJson(it.text, Map::class.java)
//            if(map.containsKey("simpleType")) simpleId = it.toString() else cardBoxId = it.toString()
//            simpleId.let { simpleId?.let { it1 ->
//                findViewById<AppCompatTextView>(R.id.tv_simple_data).text = "样:${simpleId}"
//                SharedPreferencesUtils.getSPInstance(this).putSP(Constant.SIMPLE_INFORMATION,
//                    it1
//                )
//            } }
//            cardBoxId.let { cardBoxId?.let { it1 ->
//                findViewById<AppCompatTextView>(R.id.tv_card_data).text = "卡:${cardBoxId}"
//                SharedPreferencesUtils.getSPInstance(this).putSP(Constant.CARD_BOX_INFORMATION,
//                    it1
//                )
//            } }

//            machineId = it.toString()
//            if((it.toString().first() != 'S') && (it.toString().first() != 'C')) findViewById<AppCompatTextView>(R.id.tv_scan_data).text = "无效的二维码!" else findViewById<AppCompatTextView>(R.id.tv_scan_data).text = it.toString()
            when(it.toString().first()) {
                'S' -> {
                    simpleId = it.toString()
                    SharedPreferencesUtils.getSPInstance(this).putSP(Constant.CARD_BOX_INFORMATION,it.toString())
                    findViewById<EditText>(R.id.tv_simple_data).setText(simpleId!!.substring(1))
                }
                'C' -> {
                    cardBoxId = it.toString()
                    SharedPreferencesUtils.getSPInstance(this).putSP(Constant.SIMPLE_INFORMATION,it.toString())
                    findViewById<EditText>(R.id.tv_card_data).setText(cardBoxId!!.substring(1))
                }
                else -> {
                    ToastUtil.toastShort(this,"无法识别的条形码或二维码!")
                }

            }
            return@setOnScanResultCallback true
        }
    }

    private fun showScanResultDialog(s: String) {
        val inputServer = EditText(this)
        inputServer.filters = arrayOf<InputFilter>(LengthFilter(50))
        val builder: AlertDialog.Builder = AlertDialog.Builder(this)
        builder.setTitle("Enter ID").setIcon(null)
            .setView(inputServer)
            .setNegativeButton("Cancel", null)
        builder.setPositiveButton("OK") { _, _ ->
            val sign = inputServer.text.toString()
            if (sign.isNotEmpty()) {
                //machineId = sign
                startBindActivity()
            }else {
                ToastUtil.toastShort(this,"ID IS NUll !")
            }
        }
        builder.show()
    }

    @SuppressLint("SetTextI18n")
    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.tv_dialog_show -> {
//                showScanResultDialog("")
                startBindActivity()
            }
            R.id.tv_next -> {
                startBindActivity()
            }
            R.id.iv_back -> {
                finish()
            }
        }
    }





    private fun startBindActivity() {

        if (simpleId == null || cardBoxId == null) {
            ToastUtil.toastShort(this, "ID IS NULL!")
            return
        }
        val intent = Intent(this, BindingMachineActivity::class.java)
        val startTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        SharedPreferencesUtils.getSPInstance(this).putSP(Constant.CREATE_DATE,startTime)
        intent.putExtra("data","false")
        // Log.e(Constant.TAG,machineId.toString())

        startActivity(intent)
        finish()
        }


}